package cn.liziguo.tank.script;

import cn.liziguo.tank.config.GameConfig;
import cn.liziguo.tank.factory.TankFactory;
import cn.liziguo.tank.factory.WordFactory;
import cn.liziguo.tank.util.CollidingUtils;
import cn.liziguo.tank.util.LocalTimer;
import com.almasb.fxgl.dsl.FXGL;
import com.almasb.fxgl.entity.Entity;
import com.almasb.fxgl.entity.component.Component;

/**
 * @author Liziguo
 * @date 2022/7/19 14:56
 */
public class LoadEnemyComponent extends Component {

    private final LocalTimer localTimer = new LocalTimer(System.currentTimeMillis());
    private int loaded;

    @Override
    public void onUpdate(double tpf) {
        if (loaded >= GameConfig.LEVEL_LOAD_ENEMY_COUNT) {
            entity.removeFromWorld();
            WordFactory.createMonitorWin();
            return;
        }
//        if (localTimer.elapsed(GameConfig.LEVEL_ENEMY_LOAD_INTERVAL)) {
//            final int retries = 50;
//            int i = 0;
//            while (i++ < retries) {
//                Entity entity = TankFactory.createEnemy();
//                if (CollidingUtils.isColliding(entity, FXGL.getGameWorld().getGroup(BaseTankComponent.NOT_ARMED_SHIP).getEntitiesCopy()) != null) {
//                    entity.removeFromWorld();
//                } else {
//                    loaded++;
//                    break;
//                }
//            }
////            localTimer.capture();
//        }
        if (localTimer.elapsed(GameConfig.LEVEL_ENEMY_LOAD_INTERVAL)) {
            Entity entity = TankFactory.createEnemy();
            if (CollidingUtils.isColliding(entity, FXGL.getGameWorld().getGroup(BaseTankComponent.NOT_ARMED_SHIP).getEntitiesCopy()) != null) {
                entity.removeFromWorld();
            } else {
                localTimer.capture();
                loaded++;
            }
        }
    }
}
